using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web;
using System.Web.UI.WebControls;
using iPhOwa.Exchange.ContentClasses;
using iPhOwa.Exchange.Managers;
using iPhOwa.Web.Properties;

namespace iPhOwa.Web
{
	/// <summary>
	/// Display the top level folders.
	/// </summary>
	public partial class Folders : iPhOwaPage
	{
		/// <summary>
		/// Page_Load Event
		/// </summary>
		protected void Page_Load(object sender, EventArgs e)
		{
			Title = string.Format(CultureInfo.CurrentUICulture, "Folders - {0}", Settings.Default.Title);

			Folder home = FolderManager.Get(BaseUrl, OwaSession);

			var root = new TreeNode(home.DisplayName)
			           	{
			           			ImageUrl = home.ImageUrl,
			           			NavigateUrl = "~/Folders.aspx"
			           	};

			GetChildNodes(root, BaseUrl);

			folderTree.Nodes.Add(root);
			folderTree.DataBind();
		}

		private void GetChildNodes(TreeNode parent, Uri path)
		{
			ICollection<Folder> folders = FolderManager.GetList(path, OwaSession);

			foreach(Folder folder in folders)
			{
				var node = new TreeNode(folder.DisplayName);

				if(folder.UnreadCount > 0)
				{
					node.Text += string.Format(CultureInfo.InvariantCulture, " ({0})", folder.UnreadCount);
				}

				node.ImageUrl = folder.ImageUrl;
				node.NavigateUrl = string.Format(CultureInfo.InvariantCulture, "~/ViewFolder.aspx?path={0}", HttpUtility.UrlEncode(folder.Href.ToString()));

				if(folder.HasSubs)
				{
					GetChildNodes(node, folder.Href);
				}

				parent.ChildNodes.Add(node);
			}
		}
	}
}